﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Collections;
using System.Text.RegularExpressions;
using System.Web;
using System.Threading;

namespace IYAA_BBS_SPIDER
{
    public partial class MainForm : Form
    {
        public MainForm()
        {
            InitializeComponent();
            CheckForIllegalCrossThreadCalls = false;
        }
        string domain = System.Configuration.ConfigurationSettings.AppSettings["domain"].ToString();
        int selectIndex = -1;
        string url = string.Empty;
        string formhash = string.Empty;
        string posttime = string.Empty;
        CookieContainer cc;


        /// <summary>
        /// Login AND Analyze
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void toolStripButton1_Click(object sender, EventArgs e)
        {
            if (toolStripButton1.Text == @"登陆")
            {
                Thread loginTh = new Thread(new ThreadStart(AdminLogin));
                loginTh.IsBackground = true;
                loginTh.Start();
            }
            else if (toolStripButton1.Text == @"分析")
            {

                Thread analyzeTh = new Thread(new ThreadStart(StartAnalyze));
                analyzeTh.IsBackground = true;
                analyzeTh.Start();

            }

        }


        /// <summary>
        /// Analyze html,add items to listView1
        /// </summary>
        private void StartAnalyze()
        {
            toolStripStatusLabel1.Text = "开始分析..";
            selectIndex = toolStripComboBox1.SelectedIndex;
            string title = string.Empty;
            string address = string.Empty;

            //start update listview1
            listView1.BeginUpdate();

            if (selectIndex == 0)
            {
                url = @"http://www.cnbeta.com";
                string html = Html.GetNewInstnce().GetResponseString(url);
                MatchCollection res = new Regex("(?<=<dt class=\\\"topic\\\" >)[\\s\\S]*?(?=<dd class=\\\"author\\\">)").Matches(html);
                foreach (Match m in res)
                {
                    title = new Regex("(?<=<strong>)[^<]*?(?=</strong>)").Matches(m.ToString())[0].ToString();
                    address = @"http://www.cnbeta.com" + new Regex("(?<=<a href=\\\")[^>]*?(?=\\\")").Matches(m.ToString())[0].ToString();

                    ListViewItem OptionItem = new ListViewItem(title);
                    OptionItem.SubItems.Add(address);
                    OptionItem.Tag = address;
                    listView1.Items.Add(OptionItem);
                }
                //end update listview1
                listView1.EndUpdate();
            }
            toolStripStatusLabel1.Text = "分析完成!";
            System.Threading.Thread.CurrentThread.Abort();
        }


        /// <summary>
        /// login
        /// </summary>
        private void AdminLogin()
        {
            toolStripStatusLabel1.Text = "正在登陆中..";
            toolStripButton1.Enabled = false;
            ArrayList returnList = new ArrayList();
            try
            {
                //get base cookies
                ArrayList getBaseDate = Html.GetNewInstnce().GetHtmlData(domain + @"portal.php", new CookieContainer());
                //login
                ArrayList list = Html.GetNewInstnce().PostData(@"formhash=0ec39474&referer=http%3A%2F%2Fw232374.s115-8.myverydz.com%2Fportal.php&loginfield=username&username=admin&password=3313453&questionid=0&answer=&loginsubmit=true", @"http://w232374.s115-8.myverydz.com/member.php?mod=logging&action=login&loginsubmit=yes&frommessage&loginhash=L6Z96&inajax=1", (CookieContainer)getBaseDate[0]);
                //tops page
                ArrayList getdate = Html.GetNewInstnce().GetHtmlData(domain + @"forum.php?mod=post&action=newthread&fid=2&referer=http%3A//w232374.s115-8.myverydz.com/forum.php%3Fmod%3Dviewthread%26tid%3D5%26extra%3D", (CookieContainer)list[0]);
                if (getdate.Count >= 1)
                {
                    returnList.Add(getdate[0]);
                    cc = (CookieContainer)getdate[0];
                }
                formhash = new Regex("(?<=<input type=\\\"hidden\\\"[^>]*?name=\\\"formhash\\\"[^>]*?value=\\\")[\\w]*?(?=\\\")").Matches(getdate[1].ToString())[0].ToString();
                if (!string.IsNullOrEmpty(formhash))
                {
                    returnList.Add(formhash);
                }
                posttime = new Regex("(?<=<input type=\\\"hidden\\\"[^>]*?name=\\\"posttime\\\"[^>]*?value=\\\")[\\w]*?(?=\\\")").Matches(getdate[1].ToString())[0].ToString();
                if (!string.IsNullOrEmpty(posttime))
                {
                    returnList.Add(posttime);
                }
            }
            catch
            {
                returnList = null;
            }
            if (returnList != null)
            {
                if (returnList.Count == 3)
                {
                    this.Text = @"IYAA.CC - 登陆成功";
                    toolStripButton1.Enabled = true;
                    toolStripButton1.Text = @"分析";
                    toolStripStatusLabel1.Text = "登陆成功!";
                }
            }
            else
            {
                this.Text = @"IYAA.CC - 登陆失败";
                toolStripButton1.Enabled = true;
                toolStripStatusLabel1.Text = "登陆失败,请从新登陆!";
            }
            System.Threading.Thread.CurrentThread.Abort();

            //string title = HttpUtility.UrlEncode("主题", Encoding.GetEncoding("gb2312"));
            //string content = HttpUtility.UrlEncode("内容", Encoding.GetEncoding("gb2312"));

            //发帖步骤,暂时注释
            //ArrayList postTopic = Html.GetNewInstnce().PostData(@"formhash=" + formhash + @"&posttime=" + posttime + @"&wysiwyg=1&subject=" + title + @"&message=" + content + @"&replycredit_extcredits=0&replycredit_times=1&replycredit_membertimes=1&replycredit_random=100&readperm=&price=&tags=&rushreplyfrom=&rushreplyto=&rewardfloor=&stopfloor=&creditlimit=&save=&usesig=1&allownoticeauthor=1", @"http://w232374.s115-8.myverydz.com/forum.php?mod=post&action=newthread&fid=2&extra=&topicsubmit=yes", (CookieContainer)list[0]);


        }

        /// <summary>
        /// Load
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Form1_Load(object sender, EventArgs e)
        {

            //listView1.CheckBoxes = true;//设置listView1的复选框属性为真
            //listView1.View = View.Details;//设置listView1的视图方式
            //listView1.GridLines = true;//设置listView1显示网格线
            listView1.Columns.Add("Title", 250, HorizontalAlignment.Left);//向listView1中添加“Title”列
            listView1.Columns.Add("Address", 300, HorizontalAlignment.Left);//向listView1中添加“Address”列


            //combobox
            toolStripComboBox1.Items.Add("科技新闻");//0
            toolStripComboBox1.Items.Add("本地新闻");//1
            toolStripComboBox1.Items.Add("社会新闻");//2
            toolStripComboBox1.Items.Add("体育新闻");//3
            toolStripComboBox1.Items.Add("时尚爱美");//4
            toolStripComboBox1.Items.Add("家居装修");//5
            toolStripComboBox1.Items.Add("健康养生");//6
            toolStripComboBox1.Items.Add("苗条淑女");//7
            toolStripComboBox1.Items.Add("育儿专家");//8
            toolStripComboBox1.Items.Add("美食分享");//9
            toolStripComboBox1.Items.Add("地方特产");//10
            toolStripComboBox1.Items.Add("房产信息");//11
            toolStripComboBox1.Items.Add("招聘/求职");//12
            toolStripComboBox1.Items.Add("恋爱征婚");//13
            toolStripComboBox1.Items.Add("生活服务");//14
            toolStripComboBox1.Items.Add("创业投资");//15
            toolStripComboBox1.Items.Add("心情分享吧");//16
            toolStripComboBox1.Items.Add("哎呀图吧");//17
            toolStripComboBox1.Items.Add("游戏竞技");//18
            toolStripComboBox1.Items.Add("搞笑频道");//19
            toolStripComboBox1.Items.Add("娱乐杂志");//20

            //SelectedIndex
            toolStripComboBox1.SelectedIndex = 0;

        }

        /// <summary>
        /// ALL
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void checkBox1_CheckedChanged(object sender, EventArgs e)
        {
            if (checkBox1.Checked == true)
            {
                SelectAll();
            }
            else
            {
                UnSelectAll();
            }
        }

        /// <summary>
        /// UnSelectAll
        /// </summary>
        private void UnSelectAll()
        {
            foreach (ListViewItem tempItem in listView1.Items)//循环遍历listView控件中的每一项
            {
                if (tempItem.Checked)//如果当前项处于选中状态
                {
                    tempItem.Checked = false;//设置当前项为未选中状态
                }
            }
        }

        /// <summary>
        /// SelectAll
        /// </summary>
        private void SelectAll()
        {
            foreach (ListViewItem tempItem in listView1.Items)//循环遍历listView控件中的每一项
            {
                if (tempItem.Checked == false)//如果当前项处于未选中状态
                {
                    tempItem.Checked = true;//设置当前项为选中状态
                }
            }
        }


        /// <summary>
        /// GO
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_Click(object sender, EventArgs e)
        {
            string title = string.Empty;
            string url = string.Empty;
            string html = string.Empty;
            string content = string.Empty;


            ArrayList list = GetSelectItems();
            foreach (ListViewItem item in list)
            {
                title = item.Text;
                url = item.Tag.ToString();
                html = Html.GetNewInstnce().GetResponseString(url);





                Regex regMatchContent = new Regex("(<div id=\\\"news_content\\\">)[\\s\\S]*?(?=<div class=\\\"digbox\\\">)");
                string result = regMatchContent.Matches(html)[0].ToString() + @"</div>";
                content = Html.GetNewInstnce().DoHtmlToUBB(result);



                title = HttpUtility.UrlEncode(item.Text, Encoding.GetEncoding("gb2312"));
                content = HttpUtility.UrlEncode(content, Encoding.GetEncoding("gb2312"));

                




                //发帖步骤,暂时注释
                ArrayList postTopic = Html.GetNewInstnce().PostData(@"formhash=" + formhash + @"&posttime=" + posttime
                    + @"&wysiwyg=1&subject=" + title + @"&message=" + content
                    + @"&replycredit_extcredits=0&replycredit_times=1&replycredit_membertimes=1&replycredit_random=100&readperm=&"
                    + @"price=&tags=&rushreplyfrom=&rushreplyto=&rewardfloor=&stopfloor=&creditlimit=&save=&usesig=1&allownoticeauthor=1"
                    , @"http://w232374.s115-8.myverydz.com/forum.php?mod=post&action=newthread&fid=2&extra=&topicsubmit=yes", cc);



            }



        }


        /// <summary>
        /// GetSelectItems
        /// </summary>
        /// <returns></returns>
        public ArrayList GetSelectItems()
        {
            ArrayList list = new ArrayList();
            foreach (ListViewItem tempItem in listView1.CheckedItems)//循环遍历listView控件中的每一项
            {
                list.Add(tempItem);

            }

            return list;
        }










    }
}
